# -*- coding: utf-8 -*-
# @Author: Cursor
# @Date: 2025-01-07
# @Last Modified by: Tim Liu
# @Last Modified time: 2024-01-07

# @Description: OSchema table  

from sqlalchemy import Column, String, Integer, ForeignKey, Text, Boolean
from sqlalchemy.orm import relationship, Mapped, mapped_column
from db.db_base import BaseModel
from apps.vadmin.auth.models import VadminUser

class OSchemaDB(BaseModel):
    __tablename__ = 'crewplus_oschema'
    __table_args__ = {'comment': 'Object schemas for ontology'}

    related_schema_id: Mapped[int | None] = mapped_column(
        Integer,
        ForeignKey("crewplus_oschema.id", ondelete='SET NULL'),
        nullable=True,
        comment="Related schema ID"
    )
    related_schema: Mapped["OSchemaDB"] = relationship("OSchemaDB", remote_side="OSchemaDB.id")

    name: Mapped[str] = mapped_column(String(255), nullable=False, comment="Schema name")
    description: Mapped[str] = mapped_column(Text, nullable=True, comment="Schema description")
        
    schema_type: Mapped[str] = mapped_column(String(50), nullable=True, comment="Schema type")
    schema_content: Mapped[str] = mapped_column(Text, nullable=False, comment="Schema json content")

    create_user_id: Mapped[int] = mapped_column(
        Integer,
        ForeignKey("vadmin_auth_user.id", ondelete='RESTRICT'),
        comment="Creator"
    )
    create_user: Mapped[VadminUser] = relationship(foreign_keys=create_user_id)

    schema_scope: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment="Schema scope (0: global, 1: local)")

    version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, comment="Schema version")
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, comment="Is this schema active")

    ontologies: Mapped[list["OntologyDB"]] = relationship(
        "OntologyDB",
        secondary="crewplus_ontology_schema_association",
        primaryjoin="OSchemaDB.id == crewplus_ontology_schema_association.c.schema_id",
        secondaryjoin="OntologyDB.id == crewplus_ontology_schema_association.c.ontology_id",
        back_populates="schemas"
    )

# Deferred import to avoid circular dependency
from .ontology_schema_association import ontology_schema_association
from .ontology import OntologyDB